package com.zuozhj.controller;


import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zuozhj.common.Const;
import com.zuozhj.common.Result;
import com.zuozhj.entity.SysRole;
import com.zuozhj.entity.SysUser;
import com.zuozhj.entity.SysUserRole;
import com.zuozhj.service.ISysUserRoleService;

import cn.hutool.core.util.StrUtil;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zuozhj
 * @since 2022-12-02
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends BaseController{

    @Autowired
    BCryptPasswordEncoder passwordEncoder;

    @Autowired
    ISysUserRoleService sysUserRoleService;

    @PreAuthorize("hasAuthority('sys:user:list')")
    @GetMapping("/info/{id}")
    public Result info(@PathVariable(name = "id") Long id) {

        SysUser sysUser = sysUserService.getById(id);

        Assert.notNull(sysUser, "找不到该管理员");

        List<SysRole> roles = sysRoleService.listRolesByUserId(sysUser.getId());

        sysUser.setSysroles(roles);

        return Result.success(sysUser);
    }


    @PreAuthorize("hasAuthority('sys:user:list')")
    @GetMapping("/list")
    @SuppressWarnings("unchecked") 
    public Result list(String name) {

        Page<SysUser> users = sysUserService.page(getPage(), 
                new QueryWrapper<SysUser>().like(StrUtil.isNotBlank(name), "name", name)
            );

            users.getRecords().forEach(user -> {
                user.setSysroles(sysRoleService.listRolesByUserId(user.getId()));
            });

        return Result.success(users);
    }

    @PreAuthorize("PohasAuthority('sys:user:save')")
    @PostMapping("/save")
    public Result save(@Validated @RequestBody SysUser sysUser) {

        sysUser.setCreatedAt(LocalDateTime.now());
        sysUser.setStatus(1);

        sysUser.setPassword(passwordEncoder.encode(Const.DEFAULT_PASSWORD));
        sysUser.setAvatar(Const.DEFAULT_AVATAR);

        sysUserService.save(sysUser);

        return Result.success(sysUser);
    }

    @PreAuthorize("hasAuthority('sys:user:update')")
    @PostMapping("/update")
    public Result udpate(@Validated @RequestBody SysUser sysUser) {

        sysUser.setUpdatedAt(LocalDateTime.now());

        sysUserService.updateById(sysUser);

        return Result.success(sysUser);
    }

    @PreAuthorize("hasAuthority('sys:user:delete')")
    @PostMapping("/delete")
    @Transactional          // 事务
    public Result delete(@RequestBody Long[] ids) {
        //批量删除
        sysUserService.removeByIds(Arrays.asList(ids));

        // 数据库外键关联自动删除,不需要写以下代码
        // sysUserRoleService.remove(new QueryWrapper<SysUserRole>().in("user_id", ids));

        return Result.success("");
    }


    @PreAuthorize("hasAuthority('sys:user:role')")
    @RequestMapping("/role/{userId}")
    @Transactional
    public Result perm(@PathVariable(name = "userId") Long userId, @RequestBody Long[] roleIds ) {

        List<SysUserRole> userRoles = new ArrayList<>();
       

        Arrays.stream(roleIds).forEach(roleId -> {
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(roleId);

            userRoles.add(userRole);
        });

        // 先删除中间表的数据再添加新数据
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq("user_id", userId));
        sysUserRoleService.saveBatch(userRoles);

        // 删除权限缓存
        SysUser sysUser = sysUserService.getById(userId); 
        sysUserService.clearUserAuthorityInfo(sysUser.getUsername());

        return Result.success(userRoles);
    }

    /* 
     * 初始化密码: 888888
     */
    @PreAuthorize("hasAuthority('sys:user:role')")
    @RequestMapping("/repass")
    public Result repass(@RequestBody Long userId) {

        SysUser sysUser = sysUserService.getById(userId);

        sysUser.setPassword(passwordEncoder.encode(Const.DEFAULT_PASSWORD));
        sysUser.setUpdatedAt(LocalDateTime.now());
        
        sysUserService.updateById(sysUser);

        return Result.success("");
    }

}
